// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  
  try {
    // 解析请求参数
    const { imageUrl, prompt, negativePrompt, style, size, title, description, tags } = event
    
    // 获取当前时间
    const createTime = db.serverDate()
    
    // 1. 从临时文件下载图片
    const imageRes = await cloud.downloadFile({
      fileID: imageUrl,
    })
    const buffer = imageRes.fileContent
    
    // 2. 上传到云存储的images目录
    const cloudPath = `images/${openid}_${Date.now()}.jpg`
    const uploadRes = await cloud.uploadFile({
      cloudPath,
      fileContent: buffer,
    })
    
    // 获取存储后的文件ID
    const fileID = uploadRes.fileID
    
    // 3. 将图片信息保存到数据库
    const imageData = {
      _openid: openid,
      fileID: fileID,
      title: title || prompt.slice(0, 20) + '...',
      prompt,
      negativePrompt,
      style,
      size,
      description: description || '',
      tags: tags || [],
      likeCount: 0,
      commentCount: 0,
      viewCount: 0,
      createTime,
      updateTime: createTime,
      status: 'active'
    }
    
    // 4. 插入数据库
    const addResult = await db.collection('images').add({
      data: imageData
    })
    
    // 5. 更新用户的作品计数
    await db.collection('users').where({
      _openid: openid
    }).update({
      data: {
        imageCount: _.inc(1),
        updateTime: createTime
      }
    })
    
    return {
      success: true,
      message: '图片发布成功',
      data: {
        _id: addResult._id,
        fileID
      }
    }
    
  } catch (error) {
    console.error('保存图片失败:', error)
    return {
      success: false,
      message: '图片发布失败: ' + error.message,
      error
    }
  }
} 